import request from '@/utils/request'
import type { AxiosResponse } from 'axios'

// 定义类型
export interface Topic {
  id: number
  title: string
  description: string
  requirements: string
  budget: number
  status: 'draft' | 'open' | 'closed' | 'completed'
  category: string
  tags: string[]
  enterprise_id: number
  created_at: string
  updated_at: string
  deadline: string
}

export interface TopicFormData {
  title: string
  description: string
  requirements: string
  budget: number
  deadline: string
  category: string
  tags: string[]
}

export interface Application {
  id: number
  project_id: number
  applicant_id: number
  status: 'pending' | 'approved' | 'rejected' | 'confirmed'
  cover_letter: string
  resume: string
  portfolio: string
  feedback?: string
  created_at: string
  updated_at: string
}

export interface UpdateApplicationStatusParams {
  status: 'pending' | 'approved' | 'rejected' | 'confirmed'
  feedback?: string
}

interface PaginationParams {
  page?: number
  size?: number
  status?: string
  [property: string]: any
}

export interface PaginatedResponse<T> {
  data: T[]
  total: number
  page: number
  size: number
  pages: number
}

export interface BaseResponse<T = any> {
  code: number
  message: string
  data: T
  trace_id?: string
  total?: number
  page?: number
  size?: number
  pages?: number
}

// 创建课题
export const createProject = (data: TopicFormData): Promise<BaseResponse<Topic>> => {
  return request({
    url: '/projects',
    method: 'post',
    data
  })
}

// 获取我的课题（分页）
export const getMyProjects = (params?: PaginationParams): Promise<BaseResponse<PaginatedResponse<Topic>>> => {
  return request({
    url: '/projects/my',
    method: 'get',
    params
  })
}

// 获取课题详情
export const getProjectDetail = (id: number): Promise<BaseResponse<Topic>> => {
  return request({
    url: `/projects/${id}`,
    method: 'get'
  })
}

// 更新课题
export const updateProject = (id: number, data: TopicFormData): Promise<BaseResponse<Topic>> => {
  return request({
    url: `/projects/${id}`,
    method: 'put',
    data
  })
}

// 删除课题
export const deleteProject = (id: number): Promise<BaseResponse<{}>> => {
  return request({
    url: `/projects/${id}`,
    method: 'delete'
  })
}

// 获取申请列表
export const getApplications = (params?: PaginationParams): Promise<BaseResponse<PaginatedResponse<Application>>> => {
  return request({
    url: '/applications',
    method: 'get',
    params
  })
}

// 获取申请详情
export const getApplicationDetail = (id: number): Promise<BaseResponse<Application>> => {
  return request({
    url: `/applications/${id}`,
    method: 'get'
  })
}

// 更新申请状态
export const updateApplicationStatus = (
  id: number,
  data: UpdateApplicationStatusParams
): Promise<BaseResponse<Application>> => {
  return request({
    url: `/applications/${id}`,
    method: 'put',
    data
  })
}

// 保留原AxiosResponse类型导出，供特殊场景使用
export type ApiResponse<T = any> = AxiosResponse<BaseResponse<T>>
